﻿#include "DynamicArray.h"

//5.初始化数组；
struct DynmicArr* Init_DynamicArr(int capacity)
{
	if (capacity <= 0)
	{
		return NULL;
	}
	struct DynamicArr* arr = malloc(sizeof(struct DynamicArr));
	if (NULL == arr)
	{
		return NULL;
	}
	arr->capacity = capacity;
	arr->addr = malloc(sizeof(void*) * arr->capacity);
	arr->size = 0;

	return arr;
}
//6.插入元素；
void Insert_DynamicArr(struct DynamicArr* arr, int pos, void* data)
{
	if (NULL == arr)
	{
		return;
	}
	if (NULL == data)
	{
		return;
	}

	if (pos<0 || pos>arr->size)
	{
		pos = arr->size;
	}
	//8.判断空间是否足够；
	if (arr->size >= arr->capacity)
	{
		//9.数组元素个数超过数组的容量空间个数，就申请一块更大的内存空间；
		int newCapacity = arr->capacity * 2;
		void** newSpace = malloc(sizeof(void*) * newCapacity);

		//10.将原来空间的数据拷贝到新空间；
		memcpy(newSpace, arr->addr, sizeof(void*) * arr->capacity);

		//11.释放原来空间的内存；
		free(arr->addr);

		//12.更新addr的指向；
		arr->addr = newSpace;
		arr->capacity = newCapacity;
	}

	//13.移动元素，给pos位置空出位置来；
	for (int i = arr->size - 1; i >= pos; --i)
	{
		arr->addr[i + 1] = arr->addr[i];
	}
	//14.将新元素插入到pos位置；
	arr->addr[pos] = data;
	arr->size++;
}
//7.遍历；
void Foreach_DynamicArr(struct DynamicArr* arr, void(*_callback)(void*))
{
	if (NULL == arr)
	{
		return;
	}
	if (NULL == _callback)
	{
		return;
	}
	for (int i = 0; i < arr->size; ++i)
	{
		_callback(arr->addr[i]);
	}
}


//21.按位置删除元素；
void RemoveByPos_DynamicArr(struct DynamicArr* dArr, int pos)
{
	if (NULL == dArr)
	{
		return;
	}
	if (pos<0 || pos>dArr->size - 1)
	{
		return;
	}
	for (int i = pos; i < dArr->size; ++i)
	{
		//22.就是将后一个元素赋值给pos位置，然后pos位置后的元素整体向前挪一位；
		dArr->addr[i] = dArr->addr[i + 1];
	}
	dArr->size--;
}
//23.按值删除元素；
void RemoveByValue_DynamicArr(struct DynamicArr* dArr, void* data, int(*compare)(void*, void*))
{
	if (NULL == dArr)
	{
		return;
	}
	if (NULL == data)
	{
		return;
	}
	if (NULL == compare)
	{
		return;
	}
	for (int i = 0; i < dArr->size; ++i)
	{
		//24.如果值data和dArr->addr[i]相等，就删除dArr->addr[i]；
		if (compare(dArr->addr[i], data))
		{
			RemoveByPos_DynamicArr(dArr, i);
			break;
		}
	}
}

//25.销毁动态数组dArr；
void Destroy_DynamicArr(struct DynamicArr* dArr)
{
	if (NULL == dArr)
	{
		return;
	}
	if (dArr->addr != NULL)
	{
		free(dArr->addr);
		dArr->addr = NULL;
	}
	free(dArr);
	dArr = NULL;
}